import React,{useState,useEffect} from 'react';
import {Form, Button, Modal, Row, Col, Input,Select,DatePicker,InputNumber,Upload,message } from 'antd';
const FormItem = Form.Item;
import {connect} from 'umi';
import {resultYearMonth} from '@/utils/utils';
import {UploadOutlined} from '@ant-design/icons';
import {getUploadUrl} from "@/utils/upload";
import moment from 'moment';
const {Option} = Select;

const UnitRecordFrom = (props) => {

  const {onSubmit, onCancel, visible,loading,type,currentUser,global = {},record} = props;
  const {options = {}} = global;
  const {orgTree = []} = options;
  const [form] = Form.useForm();
  const [title,setTitle] = useState(null);
  const [yearMonthList,setYearMonthList] = useState([]);
  const [fileUploadUrls, setFileUploadUrls] = useState([]);
  const [fileName, setFileName] = useState(null);
  const [fileList, setFileList] = useState([]);


  useEffect(() => {
    if(currentUser && visible){
      setTitle(record ? '编辑' : type === 'add' ? '新建' : '导入');
      setYearMonthList(resultYearMonth);
      if(record && visible){
        form.setFieldsValue({...record,assessmentYear:moment(record.assessmentYear)});
      }else{
        form.setFieldsValue({name:currentUser.name,code:currentUser.usercode});
      }
    }
  }, [visible]);

  const onFormCancel = () => {
    onCancel();
    setFileUploadUrls([]);
    form.resetFields();
  };

  const handleSubmit = async () => {
    const fieldsValue = await form.validateFields();
    onSubmit({...fieldsValue,assessmentYear:moment(fieldsValue.assessmentYear).format('YYYY'),id:record && record.id});
    form.resetFields();
    setFileUploadUrls([]);
  };

  const fileProps = {
    name: 'file',
    multiple: false,
    action: getUploadUrl(),
    data: {name: fileName,catlog:'document'},
    fileList: fileList,
    beforeUpload(file) {
      if (file.size/1024 > 10000) {
        message.error(`上传文件大小不能超过10M！`);
        return false;
      }
      setFileName(file.name)
    },
    onChange(res) {
      const {status} = res.file;
      if (status === 'done') {
        if (res.file.response.error) {
          message.success(`${res.file.response.error}`);
        } else {
          setFileUploadUrls([...fileUploadUrls, res.file.response]);
          message.success(`${res.file.name} 文件上传成功`);
        }
      } else if (status === 'error') {
        message.error(`${res.file.name} 文件上传失败`);
      }
      let files = info.fileList.filter(item => item.status);
      setFileList(files);
    },
    onRemove(info) {
      let urls = fileUploadUrls;
      let index = urls.indexOf(info.url);
      if (index > -1)
        urls.splice(index, 1);
      setFileUploadUrls(urls);
    }
  };

  const renderFooter = () => {
    return (
      <>
        <Button onClick={() => onFormCancel()}>关闭</Button>
        <Button type="primary" onClick={() => handleSubmit()} loading={loading}>保存</Button>
      </>
    )
  };

  return (
    <Modal
      width={'40%'}
      title={title+'单位月度绩效'}
      visible={visible}
      footer={renderFooter()}
      onOk={handleSubmit}
      onCancel={() => onFormCancel()}
    >
      <Form form={form} style={{ paddingTop: '24px' }} labelCol={{ span: 6 }} wrapperCol={{ span: 16 }}>
        <Row justify='center'>
          <Col span={16}>
            <FormItem name="name" label="操作人">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col span={16}>
            <FormItem name="code" label="操作人工号">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          {
            type !== 'import' ? <>
              <Col span={16}>
                <FormItem name="orgId" label="考核单位" rules={[{required: true, message: '考核单位不能为空！'}]}>
                  <Select placeholder="请选择考核单位" allowClear>
                    {orgTree?.map((item, index) => {
                      return (
                        <Option value={item.value} key={index}>
                          {item.title}
                        </Option>
                      )
                    })}
                  </Select>
                </FormItem>
              </Col>
              <Col span={16}>
                <FormItem name="performanceName" label="绩效方案名称" rules={[{required: true, message: '绩效方案名称不能为空！'}]}>
                  <Input placeholder="请输入绩效方案名称"/>
                </FormItem>
              </Col>
              <Col span={16}>
                <FormItem name="assessmentYear" label="考核年度" rules={[{required: true, message: '考核年度不能为空！'}]}>
                  <DatePicker className='widthStyle' picker="year"/>
                </FormItem>
              </Col>
              <Col span={16}>
                <FormItem name="assessmentCycle" label="考核周期" rules={[{required: true, message: '考核周期不能为空！'}]}>
                  <Select placeholder="请选择考核周期" allowClear>
                    {yearMonthList?.map((item, index) => {
                      return (
                        <Option value={item.value} key={index}>
                          {item.label}
                        </Option>
                      )
                    })}
                  </Select>
                </FormItem>
              </Col>
              <Col span={16}>
                <FormItem name="score" label="考核分数" rules={[{required: true, message: '考核分数不能为空！'}]}>
                  <InputNumber placeholder="请输入考核分数" style={{width:'100%'}} min={0} max={100}/>
                </FormItem>
              </Col>
            </> : <>
              <Col span={16}>
                <FormItem label="导入模板下载">
                  <a href='https://taicaifu.oss-cn-shenzhen.aliyuncs.com/taicaifu/20201014/34d5e8e956654520a77ea491cd5610b6----员工辞职书-模板.docx' target="_blank">下载模板(暂无)</a>
                </FormItem>
              </Col>
              <Col span={16}>
                <FormItem name='fileUrl' label="附件上传" rules={[{required: true, message: '导入附件不能为空！'}]}>
                  <Upload {...fileProps}>
                    <Button>
                      <UploadOutlined/> 点击上传附件
                    </Button>
                  </Upload>
                </FormItem>
              </Col>
            </>
          }
        </Row>
      </Form>
    </Modal>
  );
};
export default connect(({global,user}) => ({global,currentUser: user.currentUser}))(UnitRecordFrom);
